package com.yidu.ruifeng_logistics.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yidu.ruifeng_logistics.entity.*;
import com.yidu.ruifeng_logistics.service.*;
import com.yidu.ruifeng_logistics.utils.BaseMessage;
import com.yidu.ruifeng_logistics.vo.CourierVo;
import com.yidu.ruifeng_logistics.vo.DriverVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 司机表(LogisticsDriver)表控制层
 *
 * @author 肖楚科
 * @since 2021-03-18 10:19:04
 */
@RestController
@RequestMapping("logisticsDriver")
public class LogisticsDriverController {
    /**
     * 服务对象
     */
    @Resource
    private LogisticsDriverService logisticsDriverService;

    @Resource
    private LogisticsStaffService logisticsStaffService;

    @Resource
    private LogisticsCourierService logisticsCourierService;

    @Resource
    private LogisticsAreaService logisticsAreaService;

    @Resource
    private LogisticsWaybillService logisticsWaybillService;

    @Resource
    private LogisticsCarService logisticsCarService;

    @Resource
    private LogisticsOrderService logisticsOrderService;


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "根据id查询司机", notes = "返回仓库对象")
    @PostMapping("/showUpdate")
    public Map<String, Object> selectOne(Integer id) {
        Map<String, Object> map = new HashMap<>();
        LogisticsDriver driver = logisticsDriverService.queryById(id);
        LogisticsStaff staff = logisticsStaffService.queryById(driver.getStaffId());
        //code为后台判断用
        map.put("code", 0);
        //data为根据id查询的司机
        map.put("data", driver);
        //staffName为根据司机外键的员工id查询的与员工对象的员工名字
        map.put("staffName", staff.getStaffName());
        return map;
    }

    /**
     * 根据条件查询司机
     *
     * @param driverVo 司机对象
     * @return 信息对象
     */
    @ApiOperation(value = "根据条件查询全部司机", notes = "返回状态信息")
    @GetMapping("/queryAll")
    public Map<String, Object> queryAll(DriverVo driverVo, int page, int limit, String keyWord) {
        //将参数传入到分页助手
        PageHelper.startPage(page, limit);
        //将关键字参数填入司机vo对象中，用于查询
        driverVo.setKeyWord(keyWord);
        //全查出司机集合
        List<DriverVo> list = logisticsDriverService.queryAll(driverVo);
        //new一个map用于返回状态信息
        Map<String, Object> map = new HashMap<>();
        //将全查得到的DriverVo集合传入PageInfo中用于分页
        PageInfo<DriverVo> pageInfo = new PageInfo<>(list);
        //传递code和msg信息
        map.put("code", 0);
        map.put("msg", "查询成功");
        //data为使用pageinfo对象得到的所需集合
        map.put("data", pageInfo.getList());//可以直接写list
        //count使用pageinfo对象得到的所需行数
        map.put("count", pageInfo.getTotal()); //总行数
        return map;
    }

    /**
     * 根据id删除司机
     *
     * @param id id参数
     * @return 状态信息
     */
    @ApiOperation(value = "根据id删除司机", notes = "返回状态信息")
    @PostMapping("/delete")
    public BaseMessage delete(int id) {
        return logisticsDriverService.deleteById(id) ? BaseMessage.success() : BaseMessage.fail();
    }

    /**
     * 批量删除方法
     *
     * @param ids id拼接字符串
     * @return 状态信息
     */
    @ApiOperation(value = "批量删除司机", notes = "返回状态信息")
    @PostMapping("/deleteAll")
    public BaseMessage deleteAll(String ids) {
        return logisticsDriverService.deleteAll(ids) > 0 ? BaseMessage.success() : BaseMessage.fail();
    }

    /**
     * 根据id新增或者修改司机信息
     *
     * @param logisticsDriver 司机对象
     * @return 状态信息
     */
    @ApiOperation(value = "增加或修改司机", notes = "返回状态信息")
    @PostMapping("/addOrUpdate")
    public BaseMessage addOrUpdate(LogisticsDriver logisticsDriver) {
        //判断id是否为空，来进行增加或修改
        if (StringUtils.isEmpty(logisticsDriver.getDriverId())) {
            logisticsDriverService.insert(logisticsDriver);
        } else {
            logisticsDriverService.update(logisticsDriver);
        }
        return BaseMessage.success();
    }

    /**
     * 查出未关联的员工
     *
     * @return 返回状态信息
     */
    @ApiOperation(value = "查出未关联的员工", notes = "返回状态信息")
    @GetMapping("/queryStaff")
    public BaseMessage queryStaff(Integer id) {
        //将员工，司机，快递员全部查出
        List<LogisticsStaff> list = logisticsStaffService.queryAll(new LogisticsStaff());
        List<DriverVo> driverList = logisticsDriverService.queryAll(new DriverVo());
        List<CourierVo> logisticsCouriers = logisticsCourierService.queryAll(new CourierVo());
        //id长字符串
        String ids = "";
        //计数器
        int i = 0;
        //遍历司机，将id累加
        for (DriverVo driverVo : driverList) {
            //修改时回显选中的司机忽略
            if (!driverVo.getStaffId().equals(logisticsDriverService.queryById(id).getStaffId())) {
                i++;
                if (i == 0) {
                    ids += driverVo.getStaffId();
                } else {
                    ids += "," + driverVo.getStaffId();
                }
            }
        }
        //遍历快递员，将id累加
        for (CourierVo courier : logisticsCouriers) {
            if (StringUtils.hasText(ids)) {
                ids += "," + courier.getStaffId();
            } else {
                ids += courier.getStaffId();
            }
        }
        //员工集合的迭代器
        Iterator<LogisticsStaff> iterator = list.iterator();
        //遍历迭代器
        while (iterator.hasNext()) {
            //如果id长字符串中包含这次员工id，就移除，剩下的都为未关联的员工
            if (ids.contains(String.valueOf(iterator.next().getStaffId()))) {
                iterator.remove();
            }
        }

        return BaseMessage.success(list);
    }

    /**
     * 司机接单页面初始化
     * 找出一个对应的空闲运单分配给司机
     *
     * @return 所需信息集合
     */
    @ApiOperation(value = "司机接单页面初始化", notes = "返回状态信息")
    @PostMapping("/initialize")
    public Map<String, Object> initialize(HttpSession session) {
        //new一个map用于返回状态信息
        Map<String, Object> map = new HashMap<>();
        //从为login的session中拿到登录的员工
        LogisticsStaff staff = (LogisticsStaff) session.getAttribute("login");
        //根据员工id查询出司机
        LogisticsDriver driver = logisticsDriverService.queryByStaffId(staff.getStaffId());
        //查询该司机是否被分配车辆，也就是是否有运单正在进行
        if (logisticsCarService.selectByDriverId(driver.getDriverId()) == null) {
            //new一个运单对象
            LogisticsWaybill waybill = new LogisticsWaybill();
            //设置出发地（司机所在地区）和运单状态（待发车），用于查询
            waybill.setWaybillDeparture(driver.getDriverArea());
            waybill.setWaybillState("待发车");
            //全查用于查询运单
            List<LogisticsWaybill> waybillList = logisticsWaybillService.queryAll(waybill);
            //new一个车辆对象
            LogisticsCar car = new LogisticsCar();
            //设置车辆状态（空闲中）和所在地区（司机所在地区）
            car.setCarState("空闲中");
            car.setCarArea(driver.getDriverArea());
            //根据车辆状态和地区查询车辆
            List<LogisticsCar> carList = logisticsCarService.queryByStateOrArea(car);
            //判断运单集合是否为空
            if (waybillList.size() > 0) {
                //传递状态信息waybill为运单编号，departure为根据运单出发地查出的地区，bourn为根据运单目的地查出的地区
                map.put("waybill", waybillList.get(0).getWaybillId());
                map.put("departure", logisticsAreaService.queryById(Integer.parseInt(waybillList.get(0).getWaybillDeparture())).getAreaName());
                map.put("bourn", logisticsAreaService.queryById(Integer.parseInt(waybillList.get(0).getWaybillBourn())).getAreaName());
            } else {
                //为空信息都为暂无空闲运单，也没有carNum
                map.put("waybill", "暂无空闲运单");
                map.put("departure", "暂无空闲运单");
                map.put("bourn", "暂无空闲运单");
                map.put("carNum", "暂无空闲运单");
                return map;
            }
            //判断车辆集合是否为空
            if (carList.size() > 0) {
                //传递状态信息carNum为车牌号，carId为车辆id
                map.put("carNum", carList.get(0).getCarNum());
                map.put("carId", carList.get(0).getCarId());
            } else {
                //为空信息为暂无空闲车辆
                map.put("carNum", "暂无空闲车辆");
            }
            //传递状态信息state为1
            map.put("state", 1);
            //有运单正在进行的司机
        } else {
            //传递状态信息carNum为根据司机id查出的车辆的车牌号，carId为为根据司机id查出的车辆的id
            map.put("carNum", logisticsCarService.selectByDriverId(driver.getDriverId()).getCarNum());
            map.put("carId", logisticsCarService.selectByDriverId(driver.getDriverId()).getCarId());
            //new一个运单对象用于查询
            LogisticsWaybill waybill = new LogisticsWaybill();
            //将运单的车辆id设置为根据司机id查出的车辆的车辆id，将运单状态改为运输中
            waybill.setCarId(logisticsCarService.selectByDriverId(driver.getDriverId()).getCarId());
            waybill.setWaybillState("运输中");
            //判断查出的集合是否为空
            if (logisticsWaybillService.queryAll(waybill).size() > 0) {
                //传递状态信息waybill为运单编号，departure为根据运单出发地查出的地区，bourn为根据运单目的地查出的地区
                map.put("waybill", logisticsWaybillService.queryAll(waybill).get(0).getWaybillId());
                map.put("departure", logisticsAreaService.queryById
                        (Integer.parseInt( logisticsWaybillService.queryAll(waybill).get(0).getWaybillDeparture())).getAreaName());
                map.put("bourn", logisticsAreaService.queryById
                        (Integer.parseInt( logisticsWaybillService.queryAll(waybill).get(0).getWaybillBourn())).getAreaName());
            }
            //传递状态信息state为0
            map.put("state", 0);
        }
        return map;
    }

    /**
     * 司机接单
     *
     * @param waybillId 运单id
     * @param carId     车辆id
     * @return 状态信息
     */
    @ApiOperation(value = "司机接单", notes = "返回状态信息")
    @PostMapping("/driverWork")
    public Map<String, Object> driverWork(String waybillId, String carId, HttpSession session) {
        //new一个map用于返回状态信息
        Map<String, Object> map = new HashMap<>();
        //根据运单id查询出运单
        LogisticsWaybill waybill = logisticsWaybillService.queryById(Long.valueOf(waybillId));
        //设置状态为运输中，车辆id为carId，出发时间为现在
        waybill.setWaybillState("运输中");
        waybill.setCarId(Integer.parseInt(carId));
        waybill.setWaybillStartTime(LocalDateTime.now());
        //修改运单
        logisticsWaybillService.update(waybill);
        //拿到为login的session
        LogisticsStaff staff = (LogisticsStaff) session.getAttribute("login");
        //根据员工id查出司机
        LogisticsDriver driver = logisticsDriverService.queryByStaffId(staff.getStaffId());
        //根据车辆id查出车辆
        LogisticsCar car = logisticsCarService.queryById(Integer.parseInt(carId));
        //设置车辆司机id，状态为使用中
        car.setDriverId(driver.getDriverId());
        car.setCarState("使用中");
        //修改车辆
        logisticsCarService.update(car);
        //设置司机状态为工作中
        driver.setDriverState("工作中");
        //修改司机
        logisticsDriverService.update(driver);
        //根据运单id修改订单
        logisticsOrderService.updateWaybillId(waybill);
        //传递状态信息state为1
        map.put("state", 1);
        return map;
    }

    /**
     * 司机确认送达
     *
     * @param waybillId 运单id
     * @param carId     车辆id
     * @return 状态信息
     */
    @ApiOperation(value = "司机确认送达", notes = "返回状态信息")
    @PostMapping("/driverDelivery")
    public Map<String, Object> driverDelivery(String waybillId, String carId, HttpSession session) {
        //new一个map用于返回状态信息
        Map<String, Object> map = new HashMap<>();
        //根据运单id查询出运单
        LogisticsWaybill waybill = logisticsWaybillService.queryById(Long.valueOf(waybillId));
        //设置状态为已送达，到达时间为现在
        waybill.setWaybillState("已送达");
        waybill.setWaybillGetTime(LocalDateTime.now());
        //修改运单
        logisticsWaybillService.update(waybill);
        //根据车辆id查出车辆
        LogisticsCar car = logisticsCarService.queryById(Integer.parseInt(carId));
        //设置车辆司机id为0，状态为空闲中，地区为运单目的地
        car.setDriverId(0);
        car.setCarState("空闲中");
        car.setCarArea(waybill.getWaybillBourn());
        //修改车辆
        logisticsCarService.update(car);
        //拿到为login的session
        LogisticsStaff staff = (LogisticsStaff) session.getAttribute("login");
        //根据员工id查出司机
        LogisticsDriver driver = logisticsDriverService.queryByStaffId(staff.getStaffId());
        //设置司机状态为空闲中
        driver.setDriverState("空闲中");
        driver.setDriverArea(waybill.getWaybillBourn());
        //修改司机
        logisticsDriverService.update(driver);
        //根据运单id修改订单
        logisticsOrderService.updateWaybillId(waybill);
        //传递状态信息state为1
        map.put("state", 1);
        return map;
    }

}
